package top.jacktgq.itheima.netty.protocol_design.groupchat.message;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import lombok.Data;
import lombok.ToString;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.GroupSessionFactory;
import top.jacktgq.itheima.netty.protocol_design.groupchat.server.session.SessionFactory;

import java.util.List;

@Data
@ToString(callSuper = true)
public class GroupChatRequestMessage extends Message {
    private String content;
    private String groupName;
    private String from;

    public GroupChatRequestMessage() {
    }

    public GroupChatRequestMessage(String from, String groupName, String content) {
        this.content = content;
        this.groupName = groupName;
        this.from = from;
    }

    @Override
    public int getMessageType() {
        return GroupChatRequestMessage;
    }

    @Override
    public void handle(ChannelHandlerContext ctx) {
        List<Channel> membersChannel = GroupSessionFactory.getGroupSession().getMembersChannel(groupName);
        if (!membersChannel.isEmpty()) {
            Channel fromChannel = SessionFactory.getSession().getChannel(from);
            for (Channel channel : membersChannel) {
                if (!channel.equals(fromChannel)) {
                    channel.writeAndFlush(new GroupChatResponseMessage(groupName, from, content));
                }
            }
        } else {
            ctx.writeAndFlush(new GroupChatResponseMessage(false, "群聊" + groupName + "不存在"));
        }
    }
}
